package com.guyu.common.validator.constraintvalidators;

import cn.hutool.core.collection.CollUtil;
import com.guyu.common.core.util.GuyuEnumUtils;
import com.guyu.common.validator.constraints.EnumLimit;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.Setter;

import java.util.List;
import java.util.Objects;

/**
 * 校验传入值是否在枚举code范围内
 */
@Setter
public class IEnumLimitValidatorImpl implements ConstraintValidator<EnumLimit, Integer> {

    private List<Integer> codes;

    @Override
    public void initialize(EnumLimit constraintAnnotation) {
        this.codes = GuyuEnumUtils.allEnumCodes(constraintAnnotation.iEnum());
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext context) {
        if (Objects.isNull(value)) {
            return true;
        }
        return CollUtil.isNotEmpty(codes) && codes.contains(value);
    }
}
